package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.Setmeal;
import com.itheima.reggie.mapper.CategoryMapper;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishService;
import com.itheima.reggie.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    @Autowired
    DishService dishService;

    @Autowired
    SetmealService setmealService;

    /**
     * 删除某个菜品
     * 若该菜品类型下不为空，则抛出异常
     * @param categoryId
     */
    @Override
    public void removeById(Long categoryId) {
        // 获取dish的比较器
        LambdaQueryWrapper<Dish> dishLambdaQueryWrapper = new LambdaQueryWrapper<>();
        // 根据categoryId在dish表中查询菜品个数
        dishLambdaQueryWrapper.eq(Dish::getCategoryId, categoryId);
        //
        int count = dishService.count(dishLambdaQueryWrapper);
        if(count > 0) {
            // 抛出异常
            throw new CustomException("该分类下关联了菜品，无法删除");
        }

        // 获取dish的比较器
        LambdaQueryWrapper<Setmeal> setmealLambdaQueryWrapper = new LambdaQueryWrapper<>();
        // 根据categoryId在dish表中查询菜品个数
        setmealLambdaQueryWrapper.eq(Setmeal::getCategoryId, categoryId);
        //
        int count2 = setmealService.count(setmealLambdaQueryWrapper);
        if(count2 > 0) {
            // 抛出异常
            throw new CustomException("该分类下的套餐个数不为空，无法删除");
        }

        // 可以正常删除
        super.removeById(categoryId);
    }
}
